package com.beiing.tianshuai.tianshuai.mine.ui;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.SubmitIdentificationResultBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.mine.presenter.ClubIdentificationPresenter;
import com.beiing.tianshuai.tianshuai.mine.view.ClubIdentificationViewImpl;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.SPUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.widget.GlideImageLoader;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.tianshuai.gallerypic.config.GalleryConfig;
import com.tianshuai.gallerypic.config.GalleryPick;
import com.tianshuai.gallerypic.inter.IHandlerCallBack;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileCallback;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;
import okhttp3.ResponseBody;

public class ClubIdentificationActivity extends BaseActivity implements ClubIdentificationViewImpl{

    @BindView(R.id.toolbar_iv_back)
    ImageView mToolbarIvBack;
    @BindView(R.id.toolbar_tv_title)
    TextView mToolbarTvTitle;
    @BindView(R.id.toolbar_btn_publish)
    TextView mToolbarBtnPublish;
    @BindView(R.id.et_club_name)
    EditText mEtClubName;
    @BindView(R.id.et_user_name)
    EditText mEtUserName;
    @BindView(R.id.et_user_tel)
    EditText mEtUserTel;
    @BindView(R.id.rl_id_card_front)
    RelativeLayout mRlIdCardFront;
    @BindView(R.id.rl_id_card_back)
    RelativeLayout mRlIdCardBack;
    @BindView(R.id.rl_student_card)
    RelativeLayout mRlStudentCard;
    @BindView(R.id.iv_id_card_front)
    ImageView mIvIdCardFront;
    @BindView(R.id.iv_id_card_back)
    ImageView mIvIdCarBack;
    @BindView(R.id.iv_student_card)
    ImageView mIvStudentCard;

    private static final String                 TAG = "PersonalIdentificationA";
    private static final int                    PERMISSIONS_REQUEST_READ_CONTACTS = 100;
    
    private Unbinder                            mUnbinder;
    private Context                             mContext;
    private String                              mPhotoPath;                 // 图片路径
    private ImageView                           mIvSelected;                // 选择的图片容器
    private int                                 mPicIndex;                  // 选择的图片位置
    private String[]                            mImgSelected = {"","",""};  // 最终图片文件路径
    private List<File>                          mImages;                    // 文件集合
    private ClubIdentificationPresenter         mPresenter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_club_identification;
    }

    @Override
    protected void init() {
        mUnbinder = ButterKnife.bind(this);
        mContext = this;
        initToolbar();
        initPresenter();
        initListener();
    }

    private void initToolbar() {
        mToolbarIvBack.setVisibility(View.VISIBLE);
        mToolbarTvTitle.setText("社团认证");
        mToolbarBtnPublish.setVisibility(View.VISIBLE);
        mToolbarBtnPublish.setText("提交");
    }

    private void initPresenter() {
        mPresenter = new ClubIdentificationPresenter(this);
    }

    private void initListener() {
        // 提交
        mToolbarBtnPublish.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                String userName = mEtUserName.getText().toString();
                String tel = mEtUserTel.getText().toString();
                String title = mEtClubName.getText().toString();
                if (TextUtils.isEmpty(title)) {
                    showShortText("请输入社团名称");
                    return;
                }
                if (TextUtils.isEmpty(userName)) {
                    showShortText("请输入您的真实姓名");
                    return;
                }
                if (TextUtils.isEmpty(tel)) {
                    showShortText("请输入您的电话号码");
                    return;
                }
                for (String s : mImgSelected) {
                    if (TextUtils.isEmpty(s)) {
                        showShortText("请选择证件图片");
                        return;
                    }
                    LogUtils.i(s, TAG);
                }
                mImages = new ArrayList<>();
                for (String s : mImgSelected) {
                    File file = new File(s);
                    mImages.add(file);
                }
                mPresenter.getSubmitIdentificationResult(
                        UserInfoBean.getUid(mContext),
                        userName,
                        title,
                        tel,
                        mImages
                );
            }
        });

        // 身份证正面
        mRlIdCardFront.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                mIvSelected = mIvIdCardFront;
                mPicIndex = 0;
                checkSelfPermission();
            }
        });

        // 身份证反面
        mRlIdCardBack.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                mIvSelected = mIvIdCarBack;
                mPicIndex = 1;
                checkSelfPermission();
            }
        });

        // 身份证反面
        mRlStudentCard.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                mIvSelected = mIvStudentCard;
                mPicIndex = 2;
                checkSelfPermission();
            }
        });

        // 返回
        mToolbarIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUnbinder.unbind();
    }

    // 动态权限申请
    private void checkSelfPermission() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            LogUtils.i("需要授权", TAG);
            if (ActivityCompat.shouldShowRequestPermissionRationale(ClubIdentificationActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                LogUtils.i("拒绝过了", TAG);
                // 提示用户如果想要正常使用，要手动去设置中授权。
                showShortText("请在 设置-应用管理 中开启此应用的储存授权。");
            } else {
                LogUtils.i("进行授权", TAG);
                ActivityCompat.requestPermissions(ClubIdentificationActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_READ_CONTACTS);
            }
        } else {
            LogUtils.i("不需要授权", TAG);
            // 进行正常操作
            selectImage();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                LogUtils.i("同意授权", TAG);
                // 进行正常操作。
                selectImage();
            } else {
                LogUtils.i("拒绝授权", TAG);
            }
        }
    }

    private void selectImage() {
        List<String> path = new ArrayList<>();
        IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
                LogUtils.i("----------------- 选图开始 -----------------", TAG);
            }

            @Override
            public void onSuccess(List<String> photoList) {
                mPhotoPath = photoList.get(0);
                LogUtils.i(photoList.toString(), TAG);
                Tiny.FileCompressOptions tinyOptions = new Tiny.FileCompressOptions();
                Tiny.getInstance().source(mPhotoPath).asFile().withOptions(tinyOptions).compress(new FileCallback() {
                    @Override
                    public void callback(boolean isSuccess, String outfile) {
                        if (isSuccess) {
                            RequestOptions options = new RequestOptions()
                                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                                    .centerCrop();
                            Glide.with(mContext.getApplicationContext())
                                    .load(outfile)
                                    .apply(options)
                                    .into(mIvSelected);
                            mImgSelected[mPicIndex] = outfile;
                        } else {
                            showShortText("图片过大");
                        }
                    }
                });
            }

            @Override
            public void onCancel() {
                LogUtils.i("用户已取消", TAG);
            }

            @Override
            public void onFinish() {
                LogUtils.i("----------------- 选图结束 -----------------", TAG);
            }

            @Override
            public void onError() {
                LogUtils.e("----------------- 选图异常 -----------------", TAG);
            }
        };
        GalleryConfig galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())                // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)                 // 监听接口（必填）
                .provider("com.beiing.tianshuai.fileprovider")      // provider (必填)
                .pathList(path)                                     // 记录已选的图片
                .multiSelect(false)                                 // 是否多选   默认：false
                .crop(false)                                        // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .isShowCamera(true)                                 // 是否现实相机按钮  默认：false
                .filePath("/TianShuai/Pictures")                    // 图片存放路径
                .build();
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(ClubIdentificationActivity.this);
    }

    @Override
    public void showProgress() {
        CustomProgressDialog.showLoading(mContext, "正在提交，请稍后...", true);
    }

    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }

    @Override
    public void onRequestSuccess(ResponseBody bean) {
        try {
            String result = bean.string();
            Gson gson = new Gson();
            SubmitIdentificationResultBean resultBean = gson.fromJson(result, SubmitIdentificationResultBean.class);
            LogUtils.i(result, TAG);
            if (resultBean.getCode() == 200) {
                String status = String.valueOf(resultBean.getData().getNumber().getStatus());
                SPUtils.put(mContext, "identification_status", status);
                showShortText("提交成功");
                finish();
            } else {
                showShortText("上传失败，请重新提交");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        showShortText("网络异常");
    }
    
}
